package com.dgut.exp02.czqqq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableConfigurationProperties({ConfigProperties.class,MyThreadPoolConfig.class})
@Configuration
public class AutoConfig {

    @Autowired
    private Environment environment;
    @Autowired
    private MyThreadPoolConfig config;

    @Bean
    @ConditionalOnProperty(prefix = "com.dgut.exp02.czqqq" ,name = "flag",havingValue = "true")
    public CommandLineRunner creatCommandLineRunnerImpl(){
        return new CommandLineRunnerImpl(environment);
    }

    @Bean("myTestThreadPool")
    public Executor myTestThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(config.getCorePoolSize()); //配置核心线程池大小
        executor.setMaxPoolSize(config.getMaxPoolSize()); //配置最大线程数
        executor.setQueueCapacity(config.getQueueCapacity()); //配置队列容量
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());//配置线程池活跃时间
        executor.setThreadNamePrefix("myThreadPool-"); //配置线程前缀名
        executor.setWaitForTasksToCompleteOnShutdown(true);//配置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setAwaitTerminationSeconds(config.getWaitTime());//配置线程池中任务的等待时间
        return executor;
    }

    @Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    public ApplicationEventMulticaster applicationEventMulticaster(){
        SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster();
        simpleApplicationEventMulticaster.setTaskExecutor(myTestThreadPool());
        return simpleApplicationEventMulticaster;
    }


}
